package com.chengshuang.log.service;

import com.chengshuang.log.annotation.LogRecord;
import com.chengshuang.log.constant.LogConstant;
import com.chengshuang.log.context.DynamicTemplatesContext;
import com.chengshuang.log.domain.OperationLog;
import com.chengshuang.log.enums.OperationLogTypeEnum;
import com.chengshuang.log.utils.LogParseUtils;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author shuang.cheng
 * @date 2022/10/13
 * @description
 */
@Service
public class LogService {

    /**
     * 保存日志
     */
    public void record(LogRecord annotation) {
        OperationLog operationLog = buildOperationLog(annotation);

        // 获取当前登录、时间、IP等

        // 存储数据库或MQ中
        System.out.println(operationLog.toString());
    }

    private OperationLog buildOperationLog(LogRecord annotation) {
        OperationLog operationLog = new OperationLog();
        //type
        OperationLogTypeEnum type = annotation.type();
        operationLog.setType(type.getType());
        //relationId
        DynamicTemplatesContext relationIdDT = LogParseUtils.getDynamicTemplates(LogConstant.RELATION_ID);
        String relationIdResult;
        if (relationIdDT != null) {
            relationIdResult = relationIdDT.getResult();
        } else {
            relationIdResult = annotation.relationId();
        }
        operationLog.setRelationId(StringUtils.isBlank(relationIdResult) ? null : Long.valueOf(relationIdResult));
        //operatorId
        DynamicTemplatesContext operatorIdDT = LogParseUtils.getDynamicTemplates(LogConstant.OPERATOR_ID);
        String operatorIdResult;
        if (operatorIdDT != null) {
            operatorIdResult = operatorIdDT.getResult();
        } else {
            operatorIdResult = annotation.operatorId();
        }
        operationLog.setOperatorId(StringUtils.isBlank(operatorIdResult) ? null : Long.valueOf(operatorIdResult));
        //operateTime
        operationLog.setOperateTime(new Date());
        //description
        DynamicTemplatesContext descriptionDT = LogParseUtils.getDynamicTemplates(LogConstant.DESCRIPTION);
        String descriptionResult;
        if (descriptionDT != null) {
            descriptionResult = descriptionDT.getResult();
        } else {
            descriptionResult = annotation.description();
        }
        operationLog.setDescription(descriptionResult);

        return operationLog;
    }
}
